package com.dev.manager.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dev.common.base.controller.BaseController;
import com.dev.common.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
 * @Description 文件相关操作
 * @author Shiwen .Li
 * @date 2016年7月8日 下午3:10:47
 * @version V1.3.1
 */
@Controller
@RequestMapping("file")
public class FileController extends BaseController {

	/**
	 * 文件上传
	 * 
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public HashMap<String, Object> upload(
			@RequestParam("file") CommonsMultipartFile file,
			HttpServletResponse response, HttpServletRequest request) {

		HashMap<String, Object> resuMap = new HashMap<String, Object>();
		// 上传保存路径
		String realPath = request.getServletContext()
				.getRealPath("/fileupload");
		// 新名字
		String newName = UUID.randomUUID().toString().replace("-", "")
				+ StringUtil.getSubString(file.getOriginalFilename(), ".");
		try {
			resuMap.put("status", 1);
			resuMap.put("name", newName);
			file.getFileItem().write(new File(realPath, newName));
		} catch (Exception e) {
			resuMap.put("status", 0);
			logger.info("文件上传失败", e);
		}
		return resuMap;
	}

	/**
	 * 文件下载
	 * 
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "download", method = RequestMethod.GET)
	public void download(HttpServletResponse response,
			HttpServletRequest request,String fileName) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
		try {
			String path = Thread.currentThread().getContextClassLoader()
					.getResource("").getPath()
					+ "download";//这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path
					+ File.separator + fileName));
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			 // 这里主要关闭。
			os.close();
			inputStream.close();
		}catch(Exception e){
		}
	}
}
